package com.mosai.smartmedical;

import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.provider.Settings;
import androidx.core.app.NotificationManagerCompat;
import androidx.appcompat.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.mosai.smartmedical.entity.NotificationListenerEvent;
import com.mosai.smartmedical.service.MyNotificationListenerService;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Set;

public class NotificationListenerActivity extends AppCompatActivity {
    public static final String TAG = NotificationListenerActivity.class.getSimpleName();
    Intent serviceName;
    TextView tvContent;
    boolean isStart;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG, "onCreate: ");
        setContentView(R.layout.activity_notification_listener);
        tvContent = findViewById(R.id.tvContent);
        serviceName = new Intent(this, MyNotificationListenerService.class);
        EventBus.getDefault().register(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onNotificationListenerEvent(NotificationListenerEvent event) {
        if (event.type == NotificationListenerEvent.TYPE_POSTED) {
            String content = "新通知\n"
                    + "appId: " + event.pkg + "\n"
                    + "title: " + event.title + "\n"
                    + "text: " + event.text + "\n\n";
            tvContent.append(content);
        } else if (event.type == NotificationListenerEvent.TYPE_REMOVED) {
            String content = "删除通知\n"
                    + "appId: " + event.pkg + "\n"
                    + "title: " + event.title + "\n"
                    + "text: " + event.text + "\n\n";
            tvContent.append(content);
        } else if (event.type == NotificationListenerEvent.TYPE_CONNECTED) {
            tvContent.append("监听连接成功\n\n");
        } else if (event.type == NotificationListenerEvent.TYPE_DISCONNECTED) {
            tvContent.append("监听连接断开\n\n");
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        startNotificationListener();
    }

    private void startNotificationListener() {
        if (isStart) {
            return;
        }
        if (!isNotificationListenerServiceEnable()) {
            openNotificationListenSettings();
            return;
        }
        isStart = true;
        startService(serviceName);
        toggleNotificationListenerService();
    }

    // 判断是否打开了通知监听权限
    private boolean isEnabled() {
        String pkgName = getPackageName();
        final String flat = Settings.Secure.getString(getContentResolver(), "enabled_notification_listeners");
        if (!TextUtils.isEmpty(flat)) {
            final String[] names = flat.split(":");
            for (String name : names) {
                final ComponentName cn = ComponentName.unflattenFromString(name);
                if (cn != null) {
                    if (TextUtils.equals(pkgName, cn.getPackageName())) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    public void openNotificationListenSettings() {
        try {
            Intent intent;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
                intent = new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS);
            } else {
                intent = new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
            }
            startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private boolean isNotificationListenerServiceEnable() {
        Set<String> packages = NotificationManagerCompat.getEnabledListenerPackages(this);
        boolean contains = packages.contains(getPackageName());
        Log.i(TAG, "isNotificationListenerServiceEnable: contains: " + contains + " packages: " + JSON.toJSONString(packages));
        return contains;
    }

    private void toggleNotificationListenerService() {
        PackageManager pm = getPackageManager();
        pm.setComponentEnabledSetting(new ComponentName(this, MyNotificationListenerService.class), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
        pm.setComponentEnabledSetting(new ComponentName(this, MyNotificationListenerService.class), PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (isStart) {
            isStart = false;
            Log.i(TAG, "onDestroy: stopService: " + stopService(serviceName));
        }
    }
}
